<template>
    <v-container fluid class="rounded-xl" style="height: 100%;">
        <v-card class="elevation-10 " style="height: 100%;">
            <!-- 搜索区域 -->
            <v-card-text class="pb-0">
                <v-row>
                    <v-col class="d-flex align-center" cols="12" md="3">
                        <v-btn v-if="$perms('customer_customerrelation_insert')" color="primary" prepend-icon="mdi-plus"
                            :disabled="loading" @click="add">
                            新增 
                        </v-btn>
                        <div class="d-flex gap-2 ml-2"> 
                            <v-btn v-if="$perms('customer_customerrelation_import')"
                                :disabled="!selectRows.length || loading || deleteLoading" :loading="deleteLoading"
                                color="error" icon="mdi-delete" size="small" variant="outlined"
                                @click="handleDeleteBatch" />

                            <v-btn v-if="$perms('customer_customerrelation_export')" color="success" icon="mdi-download"
                                size="small" variant="outlined" :disabled="loading || exportLoading"
                                :loading="exportLoading" @click="handleExport" /> 

                            <v-btn v-if="$perms('customer_customerrelation_export')" color="info" icon="mdi-upload"
                                size="small" variant="outlined" :disabled="loading || importLoading"
                                @click="handleImport" />
                        </div>
                    </v-col>
                    <v-col cols="12" md="2">
                        <v-text-field v-model="queryParams.customerQP!.phone_LIKE" clearable density="compact"
                            hide-details label="手机号查询" placeholder="输入家长手机号" prepend-inner-icon="mdi-phone"
                            variant="outlined" />
                    </v-col>
                    <v-col cols="12" md="2">
                        <v-text-field v-model="queryParams.customerQP!.name_LIKE" clearable density="compact"
                            hide-details label="家长姓名" placeholder="输入家长姓名" prepend-inner-icon="mdi-account"
                            variant="outlined" />
                    </v-col>
                    <v-col cols="12" md="2">
                        <v-text-field v-model="queryParams.studentQP!.name_LIKE" clearable density="compact"
                            hide-details label="学生姓名" placeholder="输入学生姓名" prepend-inner-icon="mdi-school"
                            variant="outlined" />
                    </v-col>
                    <v-col cols="12" md="3">
                        <div class="d-flex gap-2">
                            <v-btn color="primary" prepend-icon="mdi-magnify" variant="flat" :loading="loading"
                                @click="fetchData">
                                查询
                            </v-btn>
                            <v-btn color="grey" prepend-icon="mdi-refresh" variant="outlined" :disabled="loading"
                                @click="resetQuery">
                                重置
                            </v-btn>
                            <v-btn variant="outlined" :disabled="loading" @click="toggleMoreQuery">
                                更多
                            </v-btn>
                        </div>
                    </v-col>
                </v-row>
            </v-card-text>

            <!-- 更多查询条件 -->
            <v-expand-transition>
                <v-card-text v-show="showMoreQuery" class="pt-0">
                    <v-divider class="mb-4"></v-divider>

                    <!-- 关系信息查询 -->
                    <div class="mb-4">
                        <h4 class="text-subtitle-1 font-weight-medium mb-3 text-primary">
                            <v-icon class="mr-2" size="16">mdi-account-group</v-icon>
                            关系信息
                        </h4>
                        <v-row>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.relationType_EQ" :items="dict['relation_type']" clearable
                                    density="compact" hide-details item-title="dictName" item-value="dictValue"
                                    label="关系类型" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.isPrimary_EQ" :items="dict['yes_no']" clearable
                                    density="compact" hide-details item-title="dictName" item-value="dictValue"
                                    label="主要联系人" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.sourceChannel_EQ" :items="channels" clearable
                                    density="compact" hide-details item-title="channelName" item-value="id" label="来源渠道"
                                    variant="outlined" />
                            </v-col>

                        </v-row>
                    </div>

                    <!-- 家长查询条件 -->
                    <div class="mb-4">
                        <h4 class="text-subtitle-1 font-weight-medium mb-3 text-primary">
                            <v-icon class="mr-2" size="16">mdi-account</v-icon>
                            家长信息
                        </h4>
                        <v-row>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.customerQP!.email_LIKE" clearable density="compact"
                                    hide-details label="家长邮箱" placeholder="输入家长邮箱" prepend-inner-icon="mdi-email"
                                    variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.customerQP!.idCard_LIKE" clearable density="compact"
                                    hide-details label="身份证号" placeholder="输入身份证号"
                                    prepend-inner-icon="mdi-card-account-details" variant="outlined" />
                            </v-col>

                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.customerQP!.status_EQ" :items="dict['customer_status']"
                                    clearable density="compact" hide-details item-title="dictName"
                                    item-value="dictValue" label="客户状态" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.customerQP!.gender_EQ" :items="dict['gender']" clearable
                                    density="compact" hide-details item-title="dictName" item-value="dictValue"
                                    label="家长性别" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.customerQP!.address_LIKE" clearable density="compact"
                                    hide-details label="家长地址" placeholder="输入家长地址" prepend-inner-icon="mdi-map-marker"
                                    variant="outlined" />
                            </v-col>
                        </v-row>
                    </div>

                    <!-- 学生查询条件 -->
                    <div class="mb-4">
                        <h4 class="text-subtitle-1 font-weight-medium mb-3 text-primary">
                            <v-icon class="mr-2" size="16">mdi-school</v-icon>
                            学生信息
                        </h4>
                        <v-row>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.studentQP!.grade_EQ" :items="dict['student_grade']"
                                    clearable density="compact" hide-details item-title="dictName"
                                    item-value="dictValue" label="学生年级" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.studentQP!.status_EQ" :items="dict['student_status']"
                                    clearable density="compact" hide-details item-title="dictName"
                                    item-value="dictValue" label="学生状态" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.studentQP!.gender_EQ" :items="dict['gender']" clearable
                                    density="compact" hide-details item-title="dictName" item-value="dictValue"
                                    label="学生性别" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.studentQP!.school_LIKE" clearable density="compact"
                                    hide-details label="学校名称" placeholder="输入学校名称" prepend-inner-icon="mdi-school"
                                    variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.studentQP!.className_EQ" clearable density="compact"
                                    hide-details label="班级名称" placeholder="输入班级名称"
                                    prepend-inner-icon="mdi-google-classroom" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.studentQP!.educationType_EQ"
                                    :items="dict['education_type']" clearable density="compact" hide-details
                                    item-title="dictName" item-value="dictValue" label="教育类型" variant="outlined" />
                            </v-col>
                        </v-row>
                    </div>

                    <!-- 时间范围查询 -->
                    <div class="mb-4">
                        <h4 class="text-subtitle-1 font-weight-medium mb-3 text-primary">
                            <v-icon class="mr-2" size="16">mdi-calendar-range</v-icon>
                            时间范围
                        </h4>
                        <v-row>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.createTime_GE" clearable density="compact"
                                    hide-details label="创建时间开始" type="date" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.createTime_LE" clearable density="compact"
                                    hide-details label="创建时间结束" type="date" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.establishDate_GE" clearable density="compact"
                                    hide-details label="建立日期开始" type="date" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.establishDate_LE" clearable density="compact"
                                    hide-details label="建立日期结束" type="date" variant="outlined" />
                            </v-col>
                        </v-row>
                    </div>
                </v-card-text>
            </v-expand-transition>
            <!-- 加载状态 -->
            <div v-if="loading" class="text-center pa-8">
                <v-progress-circular color="primary" indeterminate size="64"></v-progress-circular>
                <p class="text-grey mt-4">正在加载数据...</p>
            </div>

            <!-- 空状态 -->
            <div v-else-if="dataList.length === 0" class="text-center pa-8">
                <v-icon size="64" color="grey-lighten-2">mdi-account-group-outline</v-icon>
                <p class="text-grey-lighten-1 mt-4">暂无客户数据</p>
            </div>

            <!-- 卡片列表 -->
            <div v-else class="card-list pa-4 overflow-y-auto">
                <CustomerRelationCard v-for="item in dataList" :key="item.id" :item="item"
                    :is-selected="selectRows.includes(item.id!)"  :channel-data="channels"
                    :disabled="loading" @update:selected="(selected) => handleCardSelection(item.id!, selected)"
                    @view-details="handleViewDetails" @edit="handleEdit" @delete="handleDelete"
                    @contact="handleContact" />
            </div>

            <!-- 分页信息和控制 -->
            <v-divider v-if="!loading"></v-divider>

            <!-- 分页控件 -->
            <div v-if="!loading && dataList.length > 0" class="d-flex justify-center pb-4">
                <v-pagination size="small" v-model="queryParams.pageNo"
                    :length="Math.ceil(total / (queryParams.pageSize || 10))" :total-visible="7" :disabled="loading"
                    variant="outlined" @update:model-value="handlePageChange" />
            </div>
        </v-card>

        <!-- 编辑对话框 -->
        <CustomerStudentRelationManagementEdit ref="editRef" @fetch-data="fetchData" />

        <!-- 详情查看对话框 -->
        <CustomerStudentRelationDetailDialog ref="detailRef" />


        <!-- 记录对话框 -->
        <CustomerRecord v-model:visible="recordDialog" v-if="selectedCustomerRelationData"
            :customer-relation-data="selectedCustomerRelationData" :selectedRecordType="selectedRecordType"  />

        <!-- 文件上传对话框 -->
        <v-dialog v-model="importDialog" max-width="600px">
            <v-card>
                <v-card-title>
                    <span class="text-h6">导入Excel</span>
                </v-card-title>
                <v-card-text>
                    <v-file-input v-model="uploadFile" accept=".xlsx,.xls" label="选择Excel文件" placeholder="点击选择文件"
                        prepend-icon="mdi-file-excel" show-size variant="outlined" />
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn color="grey-darken-1" variant="text" :disabled="importLoading" @click="importDialog = false">
                        取消
                    </v-btn>
                    <v-btn color="primary" variant="text" :loading="importLoading" :disabled="!uploadFile.length"
                        @click="handleImportExcel">
                        确定导入
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-container>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import {
    getListWithDetails,
    doDelete,
    doDeleteAll,
    doExportExcel,
    doImportExcel,
    doDownloadTemplate,
    type CustomerStudentRelationModel,
    type CustomerStudentRelationQueryParams,
    type ApiResponse,
    type PageResult
} from '@/api/customer/customerrelation/CustomerStudentRelationManagementApi';
import CustomerStudentRelationManagementEdit from './components/CustomerStudentRelationManagementEdit.vue';
import CustomerStudentRelationDetailDialog from './components/CustomerStudentRelationDetailDialog.vue';

import CustomerRelationCard from './components/CustomerRelationCard.vue';
import { getDictListSync } from '@/utils/dict';
import { useMessage } from '@/composables/useMessage';
import { getChannelListSync } from '@/utils/channel';
import { type ChannelItem } from '@/utils/channel';
import CustomerRecord from '../recrod/components/CustmoerRecord.vue';
import CustomerStudentRelationManagementImport from './components/CustomerStudentRelationManagementImport.vue';

const { success: showSuccess, error: showError } = useMessage();

// 基础数据
const loading = ref(false);
const deleteLoading = ref(false);
const exportLoading = ref(false);
const importLoading = ref(false);
const dataList = ref<CustomerStudentRelationModel[]>([]);
const total = ref(0);
const selectRows = ref<string[]>([]);
const editRef = ref();
const detailRef = ref();
const addRelationRef = ref();
const importDialog = ref(false);
const uploadFile = ref<File[]>([]);
const showMoreQuery = ref(false);
const recordDialog = ref(false);
const selectedCustomerRelationData = ref<CustomerStudentRelationModel>();
const selectedRecordType = ref(0);
// 查询参数
const queryParams = reactive<CustomerStudentRelationQueryParams>({
    pageNo: 1,
    pageSize: 10,
    customerQP: {},
    studentQP: {}
});

// 字典数据
const dict = reactive({
    relation_type: [] as any[],
    yes_no: [] as any[],
    customer_type: [] as any[],
    customer_status: [] as any[],
    student_grade: [] as any[],
    student_status: [] as any[],
    source_channel: [] as any[],
    relation_status: [] as any[],
    gender: [] as any[],
    education_type: [] as any[]
});

// 渠道数据 使用ref
const channels = ref([] as ChannelItem[]);


// 获取数据
async function fetchData() {
    loading.value = true;
    try {
        // 添加调试日志
        console.log('发送查询请求，参数:', JSON.stringify(queryParams, null, 2));

        const { data } = await getListWithDetails(queryParams);
        if (data) {
            dataList.value = data.rows || [];
            total.value = data.total || 0;
        }
    } catch (error) {
        console.error('Failed to fetch data:', error);
        showError('数据获取失败');
    } finally {
        loading.value = false;
    }
}

// 重置查询
function resetQuery() {
    Object.assign(queryParams, {
        pageNo: 1,
        pageSize: 10,

        // 关系信息
        relationType_EQ: undefined,
        isPrimary_EQ: undefined,
        sourceChannel_EQ: undefined,

        // 时间范围
        createTime_GE: undefined,
        createTime_LE: undefined,
        establishDate_GE: undefined,
        establishDate_LE: undefined,

        createBy_EQ: undefined,

        // 嵌套查询参数
        customerQP: {},
        studentQP: {}
    });
    fetchData();
}

// 切换更多查询
function toggleMoreQuery() {
    showMoreQuery.value = !showMoreQuery.value;
}

// 分页处理
function handlePageChange(page: number) {
    queryParams.pageNo = page;
    fetchData();
}

function handlePageSizeChange(size: number) {
    queryParams.pageSize = size;
    queryParams.pageNo = 1;
    fetchData();
}

// 选择处理
function setSelectRows(selected: string[]) {
    selectRows.value = selected;
}

// 卡片选择处理
function handleCardSelection(itemId: string, selected: boolean) {
    if (selected) {
        if (!selectRows.value.includes(itemId)) {
            selectRows.value.push(itemId);
        }
    } else {
        const index = selectRows.value.indexOf(itemId);
        if (index > -1) {
            selectRows.value.splice(index, 1);
        }
    }
}

// 查看详情
function handleViewDetails(row: CustomerStudentRelationModel) {
    detailRef.value?.showDetail(row);
}

// 添加编辑客户
function add() {
    editRef.value?.show();
}

// 编辑
function handleEdit(row: CustomerStudentRelationModel) {
    editRef.value?.show(row);
}

// 沟通
function handleContact(row: CustomerStudentRelationModel,type:number) {
    console.log(row.id);
    selectedCustomerRelationData.value = row;
    selectedRecordType.value = type;
    recordDialog.value = true;
}

// 删除
async function handleDelete(row: CustomerStudentRelationModel) {
    if (!confirm(`确定要删除这条客户关系记录吗？`)) return;

    deleteLoading.value = true;
    try {
        const { msg } = await doDelete({ id: row.id! });
        showSuccess(msg || '删除成功');
        fetchData();
    } catch (error) {
        console.error('Delete failed:', error);
        showError('删除失败');
    } finally {
        deleteLoading.value = false;
    }
}

// 批量删除
async function handleDeleteBatch() {
    if (!selectRows.value.length) {
        showError('请选择要删除的记录');
        return;
    }

    if (!confirm(`确定要删除选中的 ${selectRows.value.length} 条记录吗？`)) return;

    deleteLoading.value = true;
    try {
        const { msg } = await doDeleteAll({ ids: selectRows.value.join(',') });
        showSuccess(msg || '批量删除成功');
        selectRows.value = [];
        fetchData();
    } catch (error) {
        console.error('Batch delete failed:', error);
        showError('批量删除失败');
    } finally {
        deleteLoading.value = false;
    }
}

// 导出
async function handleExport() {
    exportLoading.value = true;
    try {
        await doExportExcel(queryParams);
        showSuccess('导出成功');
    } catch (error) {
        console.error('Export failed:', error);
        showError('导出失败');
    } finally {
        exportLoading.value = false;
    }
}

// 导入
function handleImport() {
    importDialog.value = true;
}

// 执行导入
async function handleImportExcel() {
    if (!uploadFile.value.length) {
        showError('请选择要导入的文件');
        return;
    }

    importLoading.value = true;
    try {
        const formData = new FormData();
        formData.append('file', uploadFile.value[0]);

        const { msg } = await doImportExcel(formData as any);
        showSuccess(msg || '导入成功');
        importDialog.value = false;
        uploadFile.value = [];
        fetchData();
    } catch (error) {
        console.error('Import failed:', error);
        showError('导入失败');
    } finally {
        importLoading.value = false;
    }
}

// 下载模板
async function handleDownloadTemplate() {
    try {
        await doDownloadTemplate();
        showSuccess('模板下载成功');
    } catch (error) {
        console.error('Download template failed:', error);
        showError('模板下载失败');
    }
}



// 初始化字典数据
function initDict() {
    dict['relation_type'] = getDictListSync('relation_type') || [];
    dict['yes_no'] = getDictListSync('yes_no') || [];
    dict['customer_type'] = getDictListSync('customer_type') || [];
    dict['customer_status'] = getDictListSync('customer_status') || [];
    dict['student_grade'] = getDictListSync('student_grade') || [];
    dict['student_status'] = getDictListSync('student_status') || [];
    dict['source_channel'] = getDictListSync('source_channel') || [];
    dict['relation_status'] = getDictListSync('relation_status') || [];
    dict['gender'] = getDictListSync('gender') || [];
    dict['education_type'] = getDictListSync('education_type') || [];
}

// 初始化渠道数据
function initChannels() {
    channels.value = getChannelListSync() || [];
}

// 生命周期
onMounted(() => {
    initDict();
    initChannels();
    fetchData();
});
</script>

<style lang="scss" scoped>
.gap-2 {
    gap: 8px;
}

.gap-1 {
    gap: 4px;
}

// 卡片标题样式
.v-card-title {
    .v-icon {
        color: white !important;
    }
}
</style>
